package io.renren.modules.customer.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.exception.RenException;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.customer.dto.CustomerInfoDTO;
import io.renren.modules.customer.excel.CustomerInfoExcel;
import io.renren.modules.customer.service.CustomerInfoService;
import io.renren.modules.order.dto.OrderDTO;
import io.renren.modules.order.service.OrderService;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.service.SysRoleUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jakarta.servlet.http.HttpServletResponse;

import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 客户表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-12-07
 */
@RestController
@RequestMapping("customer/customerinfo")
@Tag(name="客户表")
public class CustomerInfoController {

    @Autowired
    private CustomerInfoService customerInfoService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private SysRoleUserService sysRoleUserService;

    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
        @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref="int") ,
        @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY,required = true, ref="int") ,
        @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref="String") ,
        @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref="String")
    })
    public Result<PageData<CustomerInfoDTO>> page(@Parameter(hidden = true) @RequestParam Map<String, Object> params){
        PageData<CustomerInfoDTO> page = customerInfoService.customerPage(params);

        return new Result<PageData<CustomerInfoDTO>>().ok(page);
    }

    @GetMapping("list")
    @Operation(summary = "获取所有的客户")
    public Result<List<CustomerInfoDTO>> list(){
        List<CustomerInfoDTO> list = customerInfoService.getAll();
        return new Result<List<CustomerInfoDTO>>().ok(list);
    }

    @GetMapping("{id}")
    @Operation(summary = "信息")
    public Result<CustomerInfoDTO> get(@PathVariable("id") Long id){
        CustomerInfoDTO data = customerInfoService.get(id);

        return new Result<CustomerInfoDTO>().ok(data);
    }

    @PostMapping
    @Operation(summary = "保存")
    @LogOperation("保存")
    public Result save(@RequestBody CustomerInfoDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        customerInfoService.customerSave(dto);

        return new Result();
    }

    @PutMapping
    @Operation(summary = "修改")
    @LogOperation("修改")
    public Result update(@RequestBody CustomerInfoDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            throw new RenException("您暂无权限修改客户信息！");
        }
        customerInfoService.customerUpdate(dto);

        return new Result();
    }

    @DeleteMapping
    @Operation(summary = "删除")
    @LogOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            throw new RenException("您暂无权限删除客户信息！");
        }
        // 是否存在绑定的客户
        List<OrderDTO> orderDtoList = orderService.getOrderByCustomerIdList(Arrays.asList(ids));
        if (CollectionUtils.isNotEmpty(orderDtoList)) {
            throw new RuntimeException("客户存在绑定的订单，无法删除");
        }
        customerInfoService.delete(ids);
        return new Result();
    }

    @GetMapping("export")
    @Operation(summary = "导出")
    @LogOperation("导出")
    public void export(@Parameter(hidden = true) @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        // 获取当前用户
        UserDetail userDetail = SecurityUser.getUser();
        // 是否具有办公室角色
        boolean officeRole = sysRoleUserService.isOfficeRole(userDetail.getId());
        if (!officeRole && userDetail.getSuperAdmin() == 0) {
            throw new RenException("您暂无权限导出客户信息！");
        }
        List<CustomerInfoDTO> list = customerInfoService.list(params);
        ExcelUtils.exportExcelToTarget(response, null, "客户表", list, CustomerInfoExcel.class);
    }

}
